<script setup>
import { ref, onMounted, computed } from 'vue';
import { getAllDepartmentsService, addDepartmentService, deleteDepartmentService,getAllHospitalsService,updateDepartmentService } from '@/api/hospital.js'; // 导入相关的API函数
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义部门列表数据
const departments = ref([]);
const hospitals = ref([]); // 存储医院列表
const dialogVisible = ref(false);
const newDepartment = ref({
    departmentId: null,
    departmentName: '',
    contactNumber: '',
    hospitalId: null, // 新增医院ID字段
    hospitalName: '' // 新增医院名称字段
});

// 定义分页相关数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(12); // 每页显示的行数

// 计算分页后的部门数据
const paginatedDepartments = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return departments.value.slice(start, start + pageSize.value);
});

// 处理页码变化
const handlePageChange = (page) => {
    currentPage.value = page;
};

// 获取所有部门信息的函数
const fetchDepartments = async () => {
    try {
        const response = await getAllDepartmentsService(); // 获取所有部门信息
        if (response.code === 0) {
            departments.value = response.data; // 更新部门数据
        } else {
            ElMessage.error(response.message || '获取部门信息失败');
        }
    } catch (error) {
        ElMessage.error('获取部门信息失败');
    }
};

// 获取所有医院信息的函数
const fetchHospitals = async () => {
    try {
        const response = await getAllHospitalsService(); // 获取所有医院信息
        if (response.code === 0) {
            hospitals.value = response.data; // 更新医院数据
        } else {
            ElMessage.error(response.message || '获取医院信息失败');
        }
    } catch (error) {
        ElMessage.error('获取医院信息失败');
    }
};

// 打开添加部门信息的对话框
const openAddDialog = () => {
    // 自动分配一个未被使用的部门ID
    const maxId = departments.value.reduce((max, department) => Math.max(max, department.departmentId || 0), 0);
    newDepartment.value = { departmentId: maxId + 1, departmentName: '', contactNumber: '', hospitalId: null }; // 重置表单并分配新ID
    dialogVisible.value = true; // 显示对话框
};

// 添加部门信息的函数
const addDepartment = async () => {
    // 验证联系电话格式
    const phonePattern = /^8-\d{6}$/; // 8-6位数字的格式
    if (!phonePattern.test(newDepartment.value.contactNumber)) {
        ElMessage.error('联系电话格式不正确，请输入格式为 8-XXXXXX 的电话');
        return;
    }

    // 验证部门ID唯一性
    const existingDepartment = departments.value.find(department => department.departmentId === newDepartment.value.departmentId);
    if (existingDepartment) {
        ElMessage.error('部门ID必须唯一，请输入一个不同的部门ID');
        return;
    }

    try {
        const response = await addDepartmentService(newDepartment.value); // 直接传递部门对象
        if (response.code === 0) {
            ElMessage.success('添加成功');
            dialogVisible.value = false; // 关闭对话框
            fetchDepartments(); // 重新获取部门列表
        } else {
            ElMessage.error(response.message || '添加失败');
        }
    } catch (error) {
        ElMessage.error('添加失败，部门id不唯一');
    }
};

// 删除部门信息的函数
const deleteDepartment = async (departmentId) => {
    try {
        await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const response = await deleteDepartmentService(departmentId);
        if (response.code === 0) {
            ElMessage.success('删除成功');
            fetchDepartments(); // 重新获取部门列表
        } else {
            ElMessage.error(response.message || '删除失败');
        }
    } catch (error) {
        ElMessage.error('删除失败');
    }
};

// 在组件挂载时获取部门和医院数据
onMounted(() => {
    fetchDepartments(); // 直接获取所有部门数据
    fetchHospitals(); // 获取所有医院数据
});

// 新增的响应式数据
const updateDialogVisible = ref(false);
const updateDepartment = ref({});

// 打开更新部门信息的对话框
const openUpdateDialog = (department) => {
    updateDepartment.value = { ...department }; // 复制原始信息
    updateDialogVisible.value = true; // 显示对话框
};

// 更新部门信息的函数
const updateDepartmentInfo = async () => {
    try {
        const response = await updateDepartmentService(updateDepartment.value); // 调用更新服务
        if (response.code === 0) {
            ElMessage.success('更新成功');
            updateDialogVisible.value = false; // 关闭对话框
            fetchDepartments(); // 重新获取部门列表
        } else {
            ElMessage.error(response.message || '更新失败');
        }
    } catch (error) {
        ElMessage.error('更新失败');
    }
};
</script>

<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加部门</el-button>
    <el-table :data="paginatedDepartments" style="width: 100%">
      <el-table-column prop="departmentId" label="部门ID" width="100" ></el-table-column>
      <el-table-column prop="departmentName" label="部门名称" width="300"></el-table-column>
      <el-table-column prop="contactNumber" label="联系电话" width="150"></el-table-column>
      <!-- <el-table-column prop="hospitalId" label="医院ID" width="100"></el-table-column> -->
      <el-table-column prop="hospitalName" label="医院名称" width="100"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="openUpdateDialog(scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="deleteDepartment(scope.row.departmentId)">删除</el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="departments.length"
      layout="total, prev, pager, next, jumper"
    />

    <!-- 添加部门信息的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加部门信息"
      width="400px"
    >
      <el-form :model="newDepartment" label-width="120px">
        <el-form-item label="部门ID">
          <el-input v-model="newDepartment.departmentId" placeholder="请输入部门ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input v-model="newDepartment.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newDepartment.contactNumber" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="医院ID">
          <el-select v-model="newDepartment.hospitalId" placeholder="请选择医院">
            <el-option
              v-for="hospital in hospitals"
              :key="hospital.hospitalId"
              :label="hospital.hospitalName"  
              :value="hospital.hospitalId"   
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDepartment">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 添加更新部门信息的对话框 -->
    <el-dialog
      v-model="updateDialogVisible"
      title="更新部门信息"
      width="400px"
    >
      <el-form :model="updateDepartment" label-width="120px">
        <el-form-item label="部门ID">
          <el-input v-model="updateDepartment.departmentId" placeholder="请输入部门ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门名称">
          <el-input v-model="updateDepartment.departmentName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="updateDepartment.contactNumber" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="医院ID">
          <el-select v-model="updateDepartment.hospitalId" placeholder="请选择医院">
            <el-option
              v-for="hospital in hospitals"
              :key="hospital.hospitalId"
              :label="hospital.hospitalName"  
              :value="hospital.hospitalId"   
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateDepartmentInfo">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 添加样式 */
</style>